const Interview = require("../models/interviewModel");
const mongooes = require("mongoose");

//添加访谈
exports.createInterview = async (req, res) => {
  try {
    const addInterview = await Interview.create(req.body);
    const newInterview = await Interview.findOne({
      _id: addInterview._id,
    }).populate("publisher");
    // 201 Created 已创建
    res.status(201).json({
      status: "success",
      data: newInterview,
    });
  } catch (err) {
    console.log("添加访谈失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//删除访谈
exports.deleteInterview = async (req, res) => {
  try {
    const id = mongooes.Types.ObjectId(req.params);
    const data = await Interview.deleteOne({ _id: id });
    res.status(200).json({
      status: "success",
      data: data,
    });
  } catch (err) {
    console.log("删除访谈失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//修改访谈
exports.updateInterview = async (req, res) => {
  try {
    const id = mongooes.Types.ObjectId(req.params);
    const editInterview = await Interview.findByIdAndUpdate(id, req.body, {
      new: true,
    });
    if (!editInterview) {
      return res.status(404).json({
        message: "修改的访谈并不存在",
      });
    }
    const newInterview = await Interview.findOne({
      _id: editInterview._id,
    }).populate("publisher");

    res.status(200).json({
      status: "success",
      data: newInterview,
    });
  } catch (err) {
    console.log("修改访谈失败", err);
    res.status(404).json({
      err,
    });
  }
};

//获取所有访谈（审核员）
exports.getAllInterview = async (req, res) => {
  try {
    const interview = await Interview.find().populate("publisher");
    res.status(200).json({
      status: "success",
      data: interview,
    });
  } catch (err) {
    console.log("获取所有访谈失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//获取指定分组的所有访谈（管理员）
exports.getInterviewByGroup = async (req, res) => {
  try {
    const interviewData = await Interview.find().populate({
      path: "publisher",
      match: { group: req.user.group },
    });
    const newInterviewData = interviewData.filter((item) => {
      return item.publisher != null;
    });
    res.status(200).json({
      status: "success",
      data: newInterviewData,
    });
  } catch (error) {
    console.log("获取指定分组的所有访谈失败"),
      res.status(404).json({
        Error: error,
      });
  }
};

//获取指定发布人的所有访谈（调查员）
exports.getInterviewByUser = async (req, res) => {
  try {
    const user_id = mongooes.Types.ObjectId(req.user._id);
    const interviewData = await Interview.find({ publisher: user_id }).populate(
      "publisher"
    );
    res.status(200).json({
      status: "success",
      data: interviewData,
    });
  } catch (error) {
    console.log("获取指定发布人的所有访谈失败"),
      res.status(404).json({
        Error: error,
      });
  }
};

//获取指定分组的所有访谈进度（管理员）
exports.getInterviewSpeedByGroup = async (req, res) => {
  try {
    //1、获得指定分组的所有访谈
    const interviewData = await Interview.find().populate({
      path: "publisher",
      match: { group: req.user.group },
    });
    const newInterviewData = interviewData.filter((item) => {
      return item.publisher != null;
    });
    //2、构造二维数组，将同一天的访谈放一块
    let interviewByDay = Object.values(
      newInterviewData.reduce((res, item) => {
        res[item.date] ? res[item.date].push(item) : (res[item.date] = [item]);
        return res;
      }, {})
    );
    //3、构造访谈进度
    let interviewSpeed = interviewByDay.map((interview) => {
      let speedData = {
        group: req.user.group,
        time: "",
        province: "",
        city: "",
        municipalInterview: 0,
        countyInterview: 0,
        townshipInterview: 0,
        villageInterview: 0,
        contactTalk: 0,
        resettlementInterview: 0,
        municipalLeaders: 0,
        municipalDepartment: 0,
        countyLeaders: 0,
        countyDepartment: 0,
        townshipLeaders: 0,
        villageCadres: 0,
        villageDoctorsAndPrincipals: 0,
        firstSecretary: 0,
        NPCdeputies: 0,
      };
      interview.map((item) => {
        switch (item.type) {
          case "市级访谈":
            speedData.municipalInterview++;
            break;
          case "县级访谈":
            speedData.countyInterview++;
            break;
          case "镇级访谈":
            speedData.townshipInterview++;
            break;
          case "村级访谈":
            speedData.villageInterview++;
            break;
          case "对接会讲话":
            speedData.contactTalk++;
            break;
          case "安置点访谈":
            speedData.resettlementInterview++;
            break;
          default:
            break;
        }
        speedData.municipalLeaders += item.municipalLeaders;
        speedData.municipalDepartment += item.municipalDepartment;
        speedData.countyLeaders += item.countyLeaders;
        speedData.countyDepartment += item.countyDepartment;
        speedData.townshipLeaders += item.townshipLeaders;
        speedData.villageCadres += item.villageCadres;
        speedData.villageDoctorsAndPrincipals +=
          item.villageDoctorsAndPrincipals;
        speedData.firstSecretary += item.firstSecretary;
        speedData.NPCdeputies += item.NPCdeputies;
        speedData.province = item.province;
        speedData.city = item.city;
        speedData.time = item.date;
      });
      return speedData;
    });
    res.status(200).json({
      status: "success",
      data: interviewSpeed,
    });
  } catch (error) {
    console.log("获取指定分组的所有访谈失败"),
      res.status(404).json({
        Error: error,
      });
  }
};
